<template>
  <div class="image-viewer">
    <div class="toolbar">
      <el-button-group>
        <el-button 
          v-for="tool in tools" 
          :key="tool.name"
          :type="activeTool === tool.name ? 'primary' : 'default'"
          @click="setActiveTool(tool.name)"
        >
          <el-icon>
            <component :is="tool.icon" />
          </el-icon>
          <span>{{ tool.label }}</span>
        </el-button>
      </el-button-group>

      <div class="window-controls">
        <span>窗宽：</span>
        <el-slider
          v-model="windowWidth"
          :min="0"
          :max="4000"
          @change="updateWindowLevel"
        />
        <span>窗位：</span>
        <el-slider
          v-model="windowCenter"
          :min="-1000"
          :max="1000"
          @change="updateWindowLevel"
        />
      </div>
    </div>

    <div class="viewer-container">
      <div ref="cornerstone" class="cornerstone-viewport"></div>
    </div>

    <div class="measurements" v-if="measurements.length">
      <h4>测量结果</h4>
      <el-table :data="measurements" size="small">
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            {{ getMeasurementType(row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="value" label="数值" width="120">
          <template #default="{ row }">
            {{ formatMeasurement(row) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ row }">
            <el-button type="danger" link @click="deleteMeasurement(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as cornerstone from '@cornerstonejs/core'
import * as cornerstoneTools from '@cornerstonejs/tools'
import {
  ZoomIn,
  ZoomOut,
  Position,
  Compass,
  Ruler,
  Crop
} from '@element-plus/icons-vue'

const props = defineProps<{
  imageId?: string // DICOM 影像的URL或标识符
}>()

const cornerstone = ref<HTMLElement | null>(null)
const activeTool = ref('pan')
const windowWidth = ref(2000)
const windowCenter = ref(0)
const measurements = ref([])

// 工具定义
const tools = [
  { name: 'pan', label: '平移', icon: Position },
  { name: 'zoom', label: '缩放', icon: ZoomIn },
  { name: 'rotate', label: '旋转', icon: Compass },
  { name: 'length', label: '长度', icon: Ruler },
  { name: 'angle', label: '角度', icon: 'angle' },
  { name: 'rectangle', label: 'ROI', icon: Crop }
]

// 初始化 Cornerstone
onMounted(async () => {
  if (!cornerstone.value) return

  await cornerstone.init()
  
  const element = cornerstone.value
  cornerstone.enable(element)

  // 初始化工具
  cornerstoneTools.init()
  cornerstoneTools.addTool(cornerstoneTools.PanTool)
  cornerstoneTools.addTool(cornerstoneTools.ZoomTool)
  cornerstoneTools.addTool(cornerstoneTools.RotateTool)
  cornerstoneTools.addTool(cornerstoneTools.LengthTool)
  cornerstoneTools.addTool(cornerstoneTools.AngleTool)
  cornerstoneTools.addTool(cornerstoneTools.RectangleROITool)

  // 设置默认工具
  setActiveTool('pan')

  // 加载影像
  if (props.imageId) {
    await loadImage(props.imageId)
  }
})

// 清理
onUnmounted(() => {
  if (cornerstone.value) {
    cornerstone.disable(cornerstone.value)
  }
})

// 加载影像
const loadImage = async (imageId: string) => {
  try {
    const image = await cornerstone.loadImage(imageId)
    cornerstone.displayImage(cornerstone.value, image)
    updateWindowLevel()
  } catch (error) {
    console.error('Failed to load image:', error)
  }
}

// 设置活动工具
const setActiveTool = (toolName: string) => {
  activeTool.value = toolName
  cornerstoneTools.setToolActive(toolName, { mouseButtonMask: 1 })
}

// 更新窗宽窗位
const updateWindowLevel = () => {
  if (!cornerstone.value) return
  
  const viewport = cornerstone.getViewport(cornerstone.value)
  if (viewport) {
    viewport.voi.windowWidth = windowWidth.value
    viewport.voi.windowCenter = windowCenter.value
    cornerstone.setViewport(cornerstone.value, viewport)
  }
}

// 获取测量类型显示名称
const getMeasurementType = (type: string) => {
  const types = {
    length: '长度',
    angle: '角度',
    rectangle: '区域'
  }
  return types[type] || type
}

// 格式化测量结果
const formatMeasurement = (measurement: any) => {
  switch (measurement.type) {
    case 'length':
      return `${measurement.value.toFixed(2)} mm`
    case 'angle':
      return `${measurement.value.toFixed(2)}°`
    case 'rectangle':
      return `${measurement.value.toFixed(2)} mm²`
    default:
      return measurement.value.toFixed(2)
  }
}

// 删除测量
const deleteMeasurement = (measurement: any) => {
  const index = measurements.value.indexOf(measurement)
  if (index > -1) {
    measurements.value.splice(index, 1)
    // 从 cornerstone 工具中删除测量
    cornerstoneTools.removeMeasurement(measurement.toolData)
  }
}
</script>

<style scoped>
.image-viewer {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #000;
}

.toolbar {
  padding: 10px;
  background-color: #fff;
  border-bottom: 1px solid var(--el-border-color-light);
  display: flex;
  gap: 20px;
  align-items: center;
}

.window-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.window-controls .el-slider {
  width: 200px;
}

.viewer-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.cornerstone-viewport {
  width: 100%;
  height: 100%;
  position: relative;
}

.measurements {
  position: absolute;
  right: 20px;
  top: 80px;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-width: 300px;
}

.measurements h4 {
  margin: 0 0 10px;
  color: var(--el-text-color-primary);
}
</style> 